const tmpl = require("./tmpl/build/template");
require("./sass/style.scss");
const defaultLogo = require("../../img/default_logo.jpg");

import imagePlugin from "../imagePlugin/image.js";
import {getClubLogo} from "../../modules/dao.js";

class PageHeader{
    constructor(club_id, is_upload){
        this.club_id = club_id;
        this.is_upload = is_upload;

        this.container = "";
        this.needRender = false;
        this.isInit = false;

        this.init();
    }

    init () {
        getClubLogo(this.club_id).then((data)=>{
            var html = tmpl("header", {
                club_name: data.name,
            });
            var dom = $.parseHTML(html);
            var that = this;
            this.image = new imagePlugin({
                container: $(dom).find("[data-club-logo]"),
                width: "80px",
                height: "80px",
                src: data.logo || defaultLogo,
                is_upload: false,
                autoUpload: true,
                url: "web/club/updateLogo/",
                eventHandler: {
                    upload: function(formData){
                        formData.append("club_id", that.club_id);
                        return true;
                    },
                    success: function(){
                        this.showFile(this.image);
                    },
                    fail: function(err){
                        alert("upload fail");
                    }
                }
            });
            this.html = dom;
            this.isInit = true;

            if(this.needRender){
                this.render(this.container);
                this.needRender = false;
            }

        }).catch((err)=>{
            console.error(err);
        });
    }

    render (container) {
        if(!this.isInit){
            this.needRender = true;
            this.container = container;
        }else{
            this.image.resume(this.is_upload);
            $(container).html(this.html);
        }
    }

}

const getPageHeader = (function(){
    var pageHeader = null;
    return function(club_id, is_upload){
        if(!pageHeader || club_id != pageHeader.club_id){
            pageHeader = new PageHeader(club_id, is_upload);
        }else{
            pageHeader.is_upload = is_upload;
        }
        return pageHeader;
    };
})();


export default getPageHeader;

